<?php
namespace app\app\controller\v1;
use app\app\model\HouseModel;
use app\app\util\BlockUtils;
use app\app\util\OnlineUtils;
use app\app\model\RoomModel;

class RoomController extends BaseController{

    /**
     * 创建房间
     */
    public function foundRoom(){
        $user_id = OnlineUtils::getUserIdBySid();
        $room = new RoomModel();
        $room->user_id = $user_id;
        $id = $room->saveRoom();
        //生成5道题目
        $house = new HouseModel();
        $data  = $house->getFight();
        BlockUtils::setFight($id,json_encode($data));
        return jsonReturn(200,'success',['room_id'=>$id]);
    }

    /**
     * 获取对战题目
     */
    public function getHouse(){
        $room_id = input('post.room_id');
        //根据room_id取5题
        $data = BlockUtils::getFight($room_id);
        return jsonReturn(200,'success',$data);
    }

    /**
     * 对战结算
     */
    public function settle(){
        $user_id = OnlineUtils::getUserIdBySid();
        $arr = input('post.');
        $room = new RoomModel();
        $room->user_id = $user_id;
        $results = $this->validate($arr,'Room');
        if(true !== $results){
            // 验证失败 输出错误信息
            return jsonReturn(402,$results);
        }
        try{
            $result = $room->settleFight($arr);
        }catch (Exception $e){
            return jsonReturn(402,$this->error());
        }
        $Room = $room->getOne($arr['room_id']);
        //房主才重置题目
        if($Room && $Room['master_id'] == $user_id){
            //生成5道题目
            $house = new HouseModel();
            $data  = $house->getFight(input('post.room_id'));
            BlockUtils::setFight(input('post.room_id'),json_encode($data));
        }
        //返回
        return jsonReturn(200,'success',['point'=>$result['point'],'reward'=>$result['reward']]);
    }


}